import uuid

from flask import Flask, render_template, request, session, flash, jsonify

from models.admin import Admin
from models.attendce import Attendce
from models.user import User

app = Flask(__name__)
app.config['SECRET_KEY'] = "123456"


@app.route("/")
def index():
    if session.get("login_id") is None:
        return render_template("/login.html")
    return render_template("/userlist.html")


@app.route('/login')
def login():
    dict_req = {'state': "No", 'id': 0}
    username = request.args.get('username')
    password = request.args.get("password")
    remember = request.args.get('remember')
    admin = Admin().admin_query(username=username, password=password)
    if admin == None:
        return jsonify(dict_req)
    else:
        session['login_id'] = str(admin[0].get("id"))
        dict_req["state"] = "YES"
        dict_req["id"] = admin[0].get("id")
    return jsonify(dict_req)


@app.route("/userlist/<string:id>")
def userlist(id):
    """
    用户列表
    :param id:
    :return:
    """
    if session['login_id'] == id:
        return render_template('/userlist.html')
    else:
        flash("请登录后再进入")
        return render_template("/login.html")


@app.route("/users")
def users():
    users = User().user_query()
    return jsonify(users)


@app.route("/attendces", methods=["GET", "POST"])
def attendces():
    """
    考勤统计
    :return:
    """
    if request.method == "GET":
        return render_template('/attendces.html')
    else:
        attendce = Attendce().attendce_list()
        return jsonify(attendce)

@app.route("/attendcelist", methods=["GET", "POST"])
def attendcelist():
    """
    考勤统计
    :return:
    """
    attendce = Attendce().attendce_list()
    return jsonify(attendce)

@app.route("/editUser")
def editUser():
    id = request.args.get('id')
    user = User().user_find_id(id)
    return jsonify(user)


@app.route("/saveUser", methods=['GET'])
def saveUser():
    print(request.args)
    body = {
        "id": request.args.get("id"),
        "viewname": request.args.get('viewname'),
        "sex": request.args.get("sex"),
        "school_id": request.args.get("school_id"),
        "department": request.args.get("department"),
        "profession": request.args.get("profession"),
        "is_active": request.args.get("is_active")
    }
    
    result = User().user_save(**body)
    
    return jsonify(result)


@app.route("/delUser", methods=["GET", "POST"])
def delUser():
    id = request.args.get("id")
    result = User().user_delete(id=id)
    return jsonify(result)


if __name__ == '__main__':
    app.run(debug=True)
